package com.starpl.mobile.android.monthunsae.november.handler;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.starpl.mobile.android.monthunsae.november.R;
import com.starpl.mobile.android.monthunsae.november.activity.CommunityCommentActivity;
import com.starpl.mobile.android.monthunsae.november.domain.UserInfo;
import com.starpl.mobile.android.platform.command.StarplCommand;
import com.starpl.mobile.android.platform.common.StarplUtil;
import com.starpl.mobile.android.platform.common.base.BaseApplication;
import com.starpl.mobile.android.platform.common.image.ImageDownloader;
import com.starpl.mobile.android.platform.common.network.HttpHandler;
import com.starpl.mobile.android.platform.component.BaseListHandler;
import com.starpl.mobile.android.platform.domain.CommunityArticle;

/**
 * 일반 커뮤니티를 위한 리스트 핸들러
 * 
 * @author 박우람, 우연화
 * @since 2011.03.10
 */
public class CommentListHandler extends BaseListHandler
{
	private static final String TAG = "CommentHandler";
	private ArrayList<CommunityArticle> mList;
	private HashMap<Integer, Integer> mBadgeMap;
	private int mNextPage;
	
	/**
	 * 기본 생성자
	 * 
	 * @param activity 엑티비티
	 * @param userId 사용자 아이디
	 * @param keywordIdx 키워드 인덱스
	 */
	public CommentListHandler(Activity activity)
	{
		super(activity);
		
		this.mList = new ArrayList<CommunityArticle>();
		this.mBadgeMap = new HashMap<Integer, Integer>();
		this.mNextPage = 1;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#getArrayList()
	 */
	@Override
	public ArrayList<?> getArrayList()
	{
		// USAGE : 반환할 리스트 객체 정의
		return mList;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#getRowView(int, android.view.View)
	 */
	@Override
	public View getRowView(int position, View convertView)
	{
		if(convertView == null)
		{
			// USAGE : 인플레이터 활용
			convertView = inflate(R.layout.community_default_row);
		}
		
		ImageView ivProfileImage = (ImageView) convertView.findViewById(R.id.community_default_row_iv_profile);
		TextView tvComment = (TextView) convertView.findViewById(R.id.community_default_row_tv_comment);
		TextView tvNickName = (TextView) convertView.findViewById(R.id.community_default_row_tv_nickname);
		TextView tvWrittenDate = (TextView) convertView.findViewById(R.id.community_default_row_tv_date);
		TextView tvReplyLabel = (TextView) convertView.findViewById(R.id.community_default_row_tv_reply_label);
		TextView tvReplyCount = (TextView) convertView.findViewById(R.id.community_default_row_tv_reply_count);
		ImageView ivThumbnail = (ImageView) convertView.findViewById(R.id.community_default_row_iv_thumbnail);
		
		TextView tvToNickName = (TextView) convertView.findViewById(R.id.community_re_reply_row_tv_to_nickname);
		LinearLayout llOriginalLayout = (LinearLayout) convertView.findViewById(R.id.community_reply_row_ll_origin_article);
		ImageView ivOriginalProfileImage = (ImageView) convertView.findViewById(R.id.community_reply_row_iv_origin_profile);
		TextView tvOriginalComment = (TextView) convertView.findViewById(R.id.community_reply_row_tv_origin_comment);
		ImageView ivBadge = (ImageView) convertView.findViewById(R.id.community_default_row_iv_badge);
		
		// 사용자 프로필
		CommunityArticle article = (CommunityArticle) mList.get(position);
		String profileUrl = StarplUtil.addSizeTag(article.getProfileImgPath(), "60", "profile");
		ImageDownloader.download(profileUrl, ivProfileImage, true);
		
		// 글
		tvComment.setText(article.getSubject());

		// 닉네임
		tvNickName.setText(article.getStarName());
		
		// 글 작성 시각
		tvWrittenDate.setText(article.getWrittenDate());
		
		// 댓글 숫자
		int replyCount = article.getReplyCount();
		if(replyCount > 0)
		{
			tvReplyLabel.setVisibility(TextView.VISIBLE);
			tvReplyCount.setVisibility(TextView.VISIBLE);
			tvReplyCount.setText("(" + article.getReplyCount() + ")");
		}
		else
		{
			tvReplyLabel.setVisibility(TextView.INVISIBLE);
			tvReplyCount.setVisibility(TextView.INVISIBLE);
		}
		
		// 첨부 이미지
		String thumbnail = article.getPostImgPath();
		if(thumbnail != null && thumbnail.length() > 0)
		{
			thumbnail = StarplUtil.addSizeTag(thumbnail, "66", "thumbnail");
			ImageDownloader.download(thumbnail, ivThumbnail);
			ivThumbnail.setVisibility(ImageView.VISIBLE);
		}
		else
		{
			ivThumbnail.setVisibility(ImageView.GONE);
		}
		
		// 글의 상태에 맞는 추가 정보 표기
		switch(article.getType())
		{
		case CommunityArticle.TYPE_ORIGINAL:
			tvToNickName.setVisibility(TextView.GONE);
			llOriginalLayout.setVisibility(LinearLayout.GONE);
			break;
		case CommunityArticle.TYPE_REPLY:
			tvToNickName.setVisibility(TextView.GONE);
			llOriginalLayout.setVisibility(LinearLayout.VISIBLE);
			thumbnail = StarplUtil.addSizeTag(article.getParentProfileImgPath(), "30", "thumbnail");
			ImageDownloader.download(thumbnail, ivOriginalProfileImage, true);
			tvOriginalComment.setText(article.getParentSubject());
			break;
		case CommunityArticle.TYPE_REPLY_OF_REPLY:
			tvToNickName.setVisibility(TextView.VISIBLE);
			tvToNickName.setText("To. " + article.getBrotherStarName());
			llOriginalLayout.setVisibility(LinearLayout.VISIBLE);
			thumbnail = StarplUtil.addSizeTag(article.getParentProfileImgPath(), "30", "thumbnail");
			ImageDownloader.download(thumbnail, ivOriginalProfileImage, true);
			tvOriginalComment.setText(article.getParentSubject());
			
			break;
		}
		
		// 배지 정보 표시
		Integer badgeType = mBadgeMap.get(article.getUserIdx());
		if(badgeType != null)
		{
			switch(badgeType)
			{
			case 1:
				ivBadge.setVisibility(ImageView.VISIBLE);
				ivBadge.setImageResource(R.drawable.icon_master);
				break;
			case 2:
				ivBadge.setVisibility(ImageView.VISIBLE);
				ivBadge.setImageResource(R.drawable.icon_senior);
				break;
			case 3:
				ivBadge.setVisibility(ImageView.VISIBLE);
				ivBadge.setImageResource(R.drawable.icon_junior);
				break;
			}
		}
		else
		{
			ivBadge.setVisibility(ImageView.GONE);
		}
		
		// 태그 입력
		convertView.setTag(position);
		
		return convertView;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#onRowClick(android.view.View)
	 */
	@Override
	public void onRowClick(View v)
	{
		UserInfo userInfo = (UserInfo) BaseApplication.getGlobalPersistent("userInfo");
		CommunityArticle article = mList.get((Integer) v.getTag());
		Bundle extras = new Bundle();
		extras.putString("userId", userInfo.getUserId());
		extras.putInt("userIdx", userInfo.getUserIdx());
		extras.putInt("postIdx", article.getPostIdx());
		extras.putString("nickname", article.getStarName());
		
		getNewActivity()
			.setBundle(extras)
			.setTargetActivity(CommunityCommentActivity.class)
			.show();
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#onRowClear()
	 */
	@Override
	public void onRowClear()
	{
		// USAGE : 리프레시등에 의하여 데이터를 삭제할경우 사용되는 로직
		mList.clear();
		mNextPage = 1;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#loadContent()
	 */
	@Override
	public void loadContent()
	{
		HttpHandler httpHandler = new HttpHandler(mParentActivity, null)
		{
			@Override
			public void didSucceed(Object result)
			{
				try
				{
					JSONObject articleObject = (JSONObject) result;
					if(!articleObject.isNull("data"))
					{
						JSONArray articleArray = articleObject.getJSONArray("data");

						// 글 리스트를 객체화 한다.
						int articleCount = articleArray.length();
						CommunityArticle article;

						for(int i = 0 ; i < articleCount ; i++)
						{
							article = new CommunityArticle(articleArray.getJSONObject(i));

							mList.add(article);
						}
					}
					else
					{
						alert("받은 댓글이 없습니다.");
					}
					
					// 다음페이지 처리를 한다.
					JSONObject pageObject = articleObject.getJSONObject("extData1");
					mNextPage = pageObject.getInt("nextPageNum");
					
					// 다음 페이지가 있을경우 자동 다음페이지를 읽을수 있도록 설정한다.
					if(mNextPage > 0)
					{
						// USAGE : 페이징처리를 하고 있고 다음페이지가 존재할 경우 다음을 호출해야 한다.
						toggleLockListView();
					}
					else
					{
						// USAGE : 푸터뷰를 삭제합니다.
						removeFooterView();
						
						// 데이터가 없을 경우 새로운 푸터를 입력
						JSONObject extData2 = articleObject.getJSONObject("extData2");
						int limitDay = extData2.getInt("limitDay");
						View vCommentFooter = inflate(R.layout.comment_footer);
						TextView tvFooterText = (TextView) vCommentFooter.findViewById(R.id.comment_footer_tv_text);
						tvFooterText.setText("최근 " + limitDay + "일까지의 새로운 댓글이 보여집니다.");
						
						setFooterView(vCommentFooter);
						showFooterView();
					}
					
					notifyDataSetChanged();
				}
				catch(JSONException e)
				{
					Log.e(TAG, e.getMessage());
				}
			}
		};
		StarplCommand.getComment(httpHandler, mNextPage++);
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#getFooterView()
	 */
	@Override
	public View getFooterView()
	{
		// USAGE : 푸터를 반환한다.
		return inflate(R.layout.community_footer);
	}

	@Override
	public void onInit()
	{
		// USAGE : 푸터뷰를 붙인다.
		showFooterView();
		
		// USAGE : 어댑터를 붙인다. 실제로 데이터와 리스트뷰가 연결된다.
		setAdapter();
		
		// USAGE : 컨텐츠 수동 호출
		loadContent();
	}
}